//
//  XiaoKaiSearchViewController.m
//  Project_A
//
//  Created by 凯 on 15/7/15.
//  Copyright (c) 2015年 zhoukaidong. All rights reserved.
//

#import "XiaoKaiSearchViewController.h"
#import "ZWYPopKeyWordsView.h"
#import "BaseHeader.h"
#import "AFNetWorkHandle.h"
#import "XiaoKaiBrand_detailsModel.h"
#import "XiaoKaiBrand_detailsCollectionViewCell.h"
#import "UIImageView+WebCache.h"
#import "SecondViewController.h"
#import "MJRefresh.h"

@interface XiaoKaiSearchViewController ()

<
UICollectionViewDataSource,
UICollectionViewDelegate,
UITextFieldDelegate
>
@property (nonatomic , retain)UITextField *textfield;

@property (nonatomic , retain)NSString *SearchStr;


@property (nonatomic , retain)UIView *Navview;

@property (nonatomic , retain)UILabel *Navlabel;

@property (nonatomic , retain)UIButton *backbutton;

@property (nonatomic , retain)UIButton *Back;

@property (nonatomic , retain)ZWYPopKeyWordsView *popKeyWordsView;

@property (nonatomic , retain)UICollectionView *collectionview;

@property (nonatomic , retain)NSMutableArray *arr;

@property (nonatomic, assign) NSInteger footer;

@end

@implementation XiaoKaiSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.arr = [NSMutableArray array];
    self.footer = 20;
    if (self.collectionview != nil) {
        
    }
    self.popKeyWordsView = [[ZWYPopKeyWordsView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT / 3.8, SCREEN_WIDTH / 1.3, self.view.frame.size.height - SCREEN_HEIGHT / 3)];
    
    void(^block)(NSString *) = ^(NSString *str) {
        self.textfield.text = str;
        [self textChangeWith:self.textfield];
    };
    self.popKeyWordsView.block = block;
    
    self.popKeyWordsView.keyWordArray = [NSMutableArray arrayWithObjects:@"服装",@"数码",@"化妆品",@"耳机",@"鼠标",@"键盘",@"SONY",@"娱乐",@"家居",@"礼物",@"穿搭",@"美食",@"书",@"美物",@"美护",@"手工",@"母婴",@"运动",@"动漫",@"男票",@"女票",@"男朋友",@"女朋友",@"同事",@"闺蜜们",@"小盆友",@"爸爸",@"妈妈",@"结婚",@"生日",@"情人节",@"中秋节",@"端午节",@"圣诞节",@"新年",@"感谢",@"毕业",@"创意",@"萌萌哒",@"小清新",@"科技范",@"奇葩",@"设计感",@"智能设备",@"毛绒公仔",@"创意礼品",@"糖果糕点",@"咖啡",@"巧克力", @"驱蚊",@"早教益智",nil];
    [self.view addSubview:self.popKeyWordsView];
    [self.popKeyWordsView changeSearchKeyWord];
    [self creatNav];
    [self getTextFiled];
    [self creatcollectionview];
    self.collectionview.hidden = YES;
    NSLog(@"%f",self.view.frame.size.height);
    
    
}
-(void)getTextFiled
{
    self.textfield = [[UITextField alloc]initWithFrame:CGRectMake(0, 64 + 5, SCREEN_WIDTH - SCREEN_WIDTH / 6.4, SCREEN_HEIGHT / 11.4)];
    self.textfield.placeholder = @"请输入您想要搜索的分类数据";
    [self.view addSubview:self.textfield];
    self.textfield.textAlignment = NSTextAlignmentCenter;
    self.textfield.textColor = [UIColor orangeColor];
    self.textfield.clearsOnBeginEditing = YES;
//    self.textfield
//    //边框宽度
//    [aview.layer setBorderWidth:1];
//    //边框颜色
//    [aview.layer setBorderColor:[UIColor blueColor].CGColor];
    self.textfield.delegate = self;
  //  self.textfield.text = self.str;
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged:) name:UITextFieldTextDidChangeNotification object:self.searchTopTextField];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(SCREEN_WIDTH - SCREEN_WIDTH / 6.4 - SCREEN_WIDTH / 16 + SCREEN_WIDTH / 32, 64 + 5, SCREEN_HEIGHT / 6.4 - SCREEN_HEIGHT / 16, SCREEN_HEIGHT / 11.4 - 5);
    [button.layer setCornerRadius:8];
    [button setTitle:@"取消" forState:UIControlStateNormal];
    button.backgroundColor = NAVCOLOR;
    button.TintColor = [UIColor whiteColor];
    [button addTarget:self action:@selector(quxiao) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textfiledChanged:) name:UITextFieldTextDidChangeNotification object:self.textfield];
    

}
-(void)quxiao
{
    self.textfield.text = @"";
    [self.textfield endEditing:YES];
    self.collectionview.hidden = YES;
    self.popKeyWordsView.hidden = NO;
    [self.popKeyWordsView changeSearchKeyWord];
    
}
-(void)creatNav
{
    self.Navview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20 )];
    self.Navview.backgroundColor = NAVCOLOR;

    self.Navlabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, 44)];
    // self.Navlabel.alpha = 0;
    self.Navlabel.backgroundColor = NAVCOLOR;
    self.Navlabel.text = @"搜索";
    self.Navlabel.numberOfLines = 0;
    self.Navlabel.font = [UIFont systemFontOfSize:21];
    self.Navlabel.textColor = [UIColor whiteColor];
    self.Navlabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.Navview];
    [self.view addSubview:self.Navlabel];
    [self getbutton];
}
-(void)getbutton
{
    self.backbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backbutton.backgroundColor = [UIColor clearColor];
    self.backbutton.frame = CGRectMake(10, 30, 20, 20);
    [self.backbutton setBackgroundImage:[UIImage imageNamed:@"iconfont-xiangzuo@2x"] forState:UIControlStateNormal];
//    self.Backbutton = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.Backbutton.backgroundColor = [UIColor orangeColor];
//    self.Backbutton.frame = CGRectMake(SCREEN_WIDTH - SCREEN_WIDTH / , <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>)
    [self.backbutton addTarget:self action:@selector(backaaa) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.backbutton];
    [self.view bringSubviewToFront:self.backbutton];
}
-(void)textfiledChanged:(NSNotification *)NOtification
{
    UITextField *text = NOtification.object;
    [self textChangeWith:text];
}

- (void)textChangeWith:(UITextField *)text
{
    if ([text.text isEqualToString:@""]) {
        self.collectionview.hidden = YES;
        self.popKeyWordsView.hidden = NO;
        
    } else {
        [self getCollectionviewData];
        self.collectionview.hidden = NO;
        self.popKeyWordsView.hidden = YES;
    }
}


-(void)getCollectionviewData
{
    NSString *str1 = @"http://api.liwushuo.com/v1/search/item?keyword=";
    NSString *str2 = @"&limit=20&offset=0&sort=";
    NSString *str3 = self.textfield.text;
    NSString *str4 = [NSString stringWithFormat:@"%@%@%@",str1
                      , str3,str2];
    self.arr = [NSMutableArray array];
    [AFNetWorkHandle GETwithAFNByURL:str4 completion:^(id result) {
        NSMutableArray *temparr = [[result objectForKey:@"data"]objectForKey:@"items"];
        for (NSDictionary *dic in temparr) {
            XiaoKaiBrand_detailsModel *model = [[XiaoKaiBrand_detailsModel alloc]initWithDic:dic];
            [self.arr addObject:model];
            NSLog(@"%@",model.cover_image_url);
        }
        [self.collectionview reloadData];
        [self.collectionview.footer endRefreshing];
    }];
    
}

-(void)getCollectionviewDataasd
{
    NSString *str1 = @"http://api.liwushuo.com/v1/search/item?keyword=";
//    NSString *str2 = @"&limit=20&offset=0&sort=";
    NSString *str5 = @"&limit=20&offset=";
    self.footer = 20;
    NSString *str7 = @"&sort=";
    NSString *str3 = self.textfield.text;
    NSString *str4 = [NSString stringWithFormat:@"%@%@%@%ld%@",str1
                      , str3,str5, self.footer, str7];
    [AFNetWorkHandle GETwithAFNByURL:str4 completion:^(id result) {
        NSMutableArray *temparr = [[result objectForKey:@"data"]objectForKey:@"items"];
        for (NSDictionary *dic in temparr) {
            XiaoKaiBrand_detailsModel *model = [[XiaoKaiBrand_detailsModel alloc]initWithDic:dic];
            [self.arr addObject:model];
            NSLog(@"%@",model.cover_image_url);
        }
        self.footer += 20;
        [self.collectionview reloadData];
        [self.collectionview.footer endRefreshing];
    }];
}
-(void)creatcollectionview
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    //collectionviewcell大小
    layout.itemSize = CGSizeMake( (SCREEN_WIDTH - 30) / 2  , SCREEN_HEIGHT / 3);
    // 上 左  下  右  间距
    layout.sectionInset = UIEdgeInsetsMake(0, 10, 5, 10);
    //头部区域大小
   // layout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, s);
    //间隙
    layout.minimumLineSpacing = 5;
    
    self.collectionview = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 84 + SCREEN_HEIGHT / 11.4 , SCREEN_WIDTH, SCREEN_HEIGHT - 84 - SCREEN_HEIGHT / 11.4) collectionViewLayout:layout];
    self.collectionview.backgroundColor = [UIColor clearColor];
    self.collectionview.delegate = self;
    self.collectionview.dataSource = self;
    [self.collectionview registerClass:[XiaoKaiBrand_detailsCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
//    [self.collectionview registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [self.view addSubview:self.collectionview];
    
    if (self.arr != nil) {
        self.collectionview.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getCollectionviewDataasd)];
    }
    self.collectionview.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getCollectionviewDataasd)];
    
    
}
-(NSInteger )numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger )collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arr.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    XiaoKaiBrand_detailsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    XiaoKaiBrand_detailsModel *model = [self.arr objectAtIndex:indexPath.row];
    NSLog(@"%@",model.name);
    cell.Model = model;
    NSLog(@"~~~~~~~~~%@", cell.Model.image_urls);
    
    return cell;
}
-(void)backaaa
{
    [self.navigationController popToRootViewControllerAnimated:YES];
    //    NSLog(@"走走走 回家喽");
    
}
//回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
//    [textField resignFirstResponder];
    [self.textfield endEditing:YES];
    return YES;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    SecondViewController *sec = [[SecondViewController alloc]init];
    XiaoKaiBrand_detailsModel *model = [self.arr objectAtIndex:indexPath.row];
    sec.web = model.IDstr;
    sec.imageName = model.cover_image_url;
    sec.labeltext = model.name;
    [self.navigationController pushViewController:sec animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
